<?php

declare(strict_types=1);

namespace app\api\controller;

use app\api\controller\Base;
use app\common\model\Collect;
use app\common\model\Give;
use app\common\model\Goods as Goodsmodel;
use app\common\model\GoodsList;
use app\common\model\ItemCard;
use app\common\model\Shang;
use app\common\model\User;
use app\common\model\Order;
use app\common\model\OrderList;
use app\common\model\UserVip;
use think\facade\Db;
use app\common\model\CouponReceive as CouponReceiveModel;
use \think\Request;

class Infinite extends Base
{
    static $shang_prize_id = [34, 38]; #抽奖赏品id

    /**
     * 商品详情
     */
    public function infinite_goodsdetail(Request $request)
    {
        $user_info = $this->getUser();
        $goods_id = request()->param('goods_id/d', 0);
        $goods = Goodsmodel::field('id,title,imgurl_detail,price,stock,sale_stock,lock_is,type,status,addtime,rage_is,rage,item_card_id,lingzhu_is,is_shou_zhe')
            ->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        $goods['addtime'] = date('Y-m-d H:i:s', $goods['addtime']);
        $goods['imgurl_detail'] = imageUrl($goods['imgurl_detail']);

        //重抽卡
        $goods['item_card'] = (object) [];
        $goods['user_rage_schedule'] = 0;
        $goods['user_rage'] = 0;
        $goods['item_card_info'] = '';
        if ($goods['rage_is'] == 1 && $goods['item_card_id'] > 0) {
            $item_card = ItemCard::field('id,type,title')->where(['id' => $goods['item_card_id'], 'status' => 1])->find();
            if ($item_card) {
                $goods['item_card'] = $item_card;
                $goods['item_card_info'] = '重抽卡说明: 怒气值达到' . $goods['rage'] . '时, 获得重抽卡';
                //当前盒子的怒气值
                $user_rage = Db::name('user_rage')->field('id,rage')->where(['user_id' => $user_info['id'], 'goods_id' => $goods_id])->find();
                $goods['user_rage'] = $user_rage ? $user_rage['rage'] : 0;
                //怒气值进度
                if (!$user_rage || $user_rage['rage'] <= 0) {
                    $goods['user_rage_schedule'] = 0;
                } else {
                    $goods['user_rage_schedule'] = round($user_rage['rage'] / $goods['rage'] * 100);;
                }
            }
        }


        #一发
        $goods['price_one']     = (bcmul("{$goods['price']}", "1", 2)) * 1;
        #三发
        $goods['price_three']   = (bcmul("{$goods['price']}", "3", 2)) * 1;
        #五连发
        $goods['price_five']    = (bcmul("{$goods['price']}", "5", 2)) * 1;
        #十连发
        $goods['price_ten']     = (bcmul("{$goods['price']}", "10", 2)) * 1;
        #五十发
        $goods['price_five_ten'] = (bcmul("{$goods['price']}", "50", 2)) * 1;
        #是否收藏
        $collection_is = Collect::field('id')
            ->where(['user_id' => $user_info['id']])
            ->where(['goods_id' => $goods_id])
            ->where(['num' => 0])
            ->find();
        $goods['collection_is'] = $collection_is ? 1 : 0;
        if ($goods['type'] == 7) {
            $goods['need_draw_num'] = 1;
        }
        #当前热度
        $join_user = OrderList::field('user_id')
            ->append(['userinfo'])
            ->where('goods_id', '=', $goods_id)
            ->where('order_type', '=', $goods['type'])
            ->order('id desc')
            ->group('user_id')
            ->limit(5)
            ->select();
        $new_join_user = [];
        foreach ($join_user as $join_user_value) {
            $new_join_user[] = imageUrl($join_user_value['userinfo']['headimg']);
        }
        $goods['join_user'] = $new_join_user;
        #参与次数
        $join_count1 = OrderList::field('id')->where('goods_id', '=', $goods_id)
            ->where('shang_id', 'between', [34, 38])
            ->where('order_type', '=', $goods['type'])
            ->where('source', '=', 1)
            ->count();
        $goods['join_count'] = $join_count1;

        #赏池分类
        $goodslist = GoodsList::field('goods_id,shang_id')
            ->append(['shang_info', 'goods_list'])
            ->where(['goods_id' => $goods_id])
            ->where(['num' => 0])
            ->order('sort desc,shang_id asc,id asc')
            ->group('shang_id')
            ->select()->toArray();
        $total_gailv = GoodsList::where(['goods_id' => $goods_id])
            ->where(['num' => 0])->sum('gailv');

        $total_reveal_gailv = GoodsList::where(['goods_id' => $goods_id])
            ->where(['num' => 0])->sum('reveal_gailv');
        // dd($goodslist);
        foreach ($goodslist as &$value) {
            // $value['pro'] = '概率:' . (array_sum(array_column($value['goods_list'], 'gailv')) / $total_gailv ) . '%';
            $shang_gailv = array_sum(array_column($value['goods_list'], 'gailv'));
            // $value['pro'] = '概率:' . bcmul(bcdiv("$shang_gailv", "$total_gailv", 6), '100', 3) . '%';

            $shang_reveal_gailv = array_sum(array_column($value['goods_list'], 'reveal_gailv'));
            if($total_reveal_gailv){
                $value['pro'] = '概率:' . bcmul(bcdiv("$shang_reveal_gailv", "$total_reveal_gailv", 6), '100', 3) . '%';
            }else{
                $value['pro'] = '概率:' . bcmul(bcdiv("$shang_gailv", "$total_gailv", 6), '100', 3) . '%';
            }
            $value['shang_reveal_gailv'] = $shang_reveal_gailv;
            $value['total_reveal_gailv'] = $total_reveal_gailv;
            $value['shang_title'] = $value['shang_info']['title'];
            $value['shang_imgurl'] = $value['shang_info']['imgurl'];
            $value['shang_color'] = $value['shang_info']['color'];
            unset($value['shang_info']);
        }
        $goods_list = GoodsList::field('goods_id,shang_id,title,imgurl,price,real_pro,gailv,reveal_gailv, stock, sc_money,goods_type,sale_time')
            ->append(['shang_info', 'goods_list'])
            ->withAttr('imgurl', function ($value, $data) {
                return imageUrl($value);
            })
            ->where(['goods_id' => $goods_id])
            ->where(['num' => 0])
            ->order('sort desc,shang_id asc,id asc')
            ->paginate(1000);
        foreach ($goods_list as &$value) {
            #预售时间
            if ($value['sale_time']) {
                $value['sale_time'] = date('Y-m-d', $value['sale_time']);
            }
            $value['shang_title'] = $value['shang_info']['title'];
            $value['shang_imgurl'] = $value['shang_info']['imgurl'];
            $value['shang_color'] = $value['shang_info']['color'];
            unset($value['shang_info']);
        }

        $new_data = [
            'goods' => $goods,
            'goodslist' => $goodslist,
            'goods_list' => $goods_list,
            'draw_num' => $user_info['draw_num'] #优惠券的数量
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }

    /**
     * 连击赏详情
     */
    public function infinite_goodsdetail2(Request $request)
    {
        $user_info = $this->getUser();
        $goods_id = request()->param('goods_id/d', 0);
        $type = request()->param('type/d', 1);
        $goods = Goodsmodel::field('id,title,imgurl_detail,price,stock,sale_stock,lock_is,type,status,addtime,lian_ji_num,lian_ji_shang_id,is_shou_zhe')
            ->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        if (!in_array($type, [0, 1])) {
            return $this->renderError("参数错误");
        }
        $goods['addtime'] = date('Y-m-d H:i:s', $goods['addtime']);
        $goods['imgurl_detail'] = imageUrl($goods['imgurl_detail']);

        $base = getConfig('base');
        #最大发数
        $goods['max_fa'] = $base['lianji_max_num'];
        //用户秘宝次数
        $goods['user_mb_number'] = $user_info['mb_number'];
        //用户连击次数
        $lian_ji_number = Db::name('user_goods_lian_ji')->where([['user_id', '=', $user_info['id']], ['goods_id', '=', $goods_id]])->whereNull('deltime')->order('id', 'desc')->limit(1)->value('number');
        $goods['user_lian_ji_number'] = $lian_ji_number ? $lian_ji_number : 0;

        #是否收藏
        $collection_is = Collect::field('id')
            ->where(['user_id' => $user_info['id']])
            ->where(['goods_id' => $goods_id])
            ->where(['num' => 0])
            ->find();
        $goods['collection_is'] = $collection_is ? 1 : 0;

        #当前热度
        $join_user = OrderList::field('user_id')
            ->append(['userinfo'])
            ->where('goods_id', '=', $goods_id)
            ->where('order_type', '=', $goods['type'])
            ->where('source', '=', 1)
            ->order('id desc')
            ->group('user_id')
            ->limit(5)
            ->select();
        $new_join_user = [];
        foreach ($join_user as $join_user_value) {
            $new_join_user[] = $join_user_value['userinfo']['headimg'];
        }
        $goods['join_user'] = $new_join_user;
        #参与次数
        $join_count1 = OrderList::field('id')->where('goods_id', '=', $goods_id)
            ->where('shang_id', 'between', [34, 38])
            ->where('order_type', '=', $goods['type'])
            ->where('source', '=', 1)
            ->count();
        $goods['join_count'] = $join_count1;

        #赏池分类
        $goodslist = GoodsList::field('goods_id,shang_id')
            ->append(['shang_info', 'goods_list'])
            ->where(['goods_id' => $goods_id])
            ->where(['lian_ji_type' => $type])
            ->where(['num' => 0])
            ->order('sort desc,shang_id asc,id asc')
            ->group('shang_id')
            ->select()->toArray();
        $total_gailv = GoodsList::where(['goods_id' => $goods_id])->where(['lian_ji_type' => $type])
            ->where(['num' => 0])->sum('gailv');
        foreach ($goodslist as &$value) {
            // $value['pro'] = '概率:' . array_sum(array_column($value['goods_list'], 'real_pro')) . '%';
            $shang_gailv = array_sum(array_column($value['goods_list'], 'gailv'));
            $value['pro'] = '概率:' . bcmul(bcdiv("$shang_gailv", "$total_gailv", 6), '100', 3) . '%';
            $value['shang_title'] = $value['shang_info']['title'];
            $value['shang_imgurl'] = $value['shang_info']['imgurl'];
            $value['shang_color'] = $value['shang_info']['color'];
            unset($value['shang_info']);
        }
        $goods_list = GoodsList::field('goods_id,shang_id,title,imgurl,price,real_pro,sc_money')
            ->append(['shang_info', 'goods_list'])
            ->withAttr('imgurl', function ($value, $data) {
                return imageUrl($value);
            })
            ->where(['goods_id' => $goods_id])
            ->where(['lian_ji_type' => $type])
            ->where(['num' => 0])
            ->order('sort desc,shang_id asc,id asc')
            ->paginate(1000);
        foreach ($goods_list as &$value) {
            $value['shang_title'] = $value['shang_info']['title'];
            $value['shang_imgurl'] = $value['shang_info']['imgurl'];
            $value['shang_color'] = $value['shang_info']['color'];
            unset($value['shang_info']);
        }

        $new_data = [
            'goods' => $goods,
            'goodslist' => $goodslist,
            'goods_list' => $goods_list,
            'draw_num' => $user_info['draw_num'] #优惠券的数量
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }

    /**
     * 中赏记录
     */
    public function infinite_shang_log(Request $request)
    {
        $shang_id = request()->param('shang_id/d', 0);
        $goods_id = request()->param('goods_id/d', 0);
        $is_mibao = request()->param('is_mibao/d', 0);
        #盒子信息
        $goods = Goodsmodel::field('id,stock,status,type')
            ->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        #中奖记录分类
        $where = [];
        $where[] = ['goods_id', '=', $goods_id];
        $where[] = ['num', '=', 0];
        if ($is_mibao == 1) {
            $where[] = ['lian_ji_type', '=', 1];
        }
        $category = GoodsList::field('shang_id')
            ->append(['shang_title'])
            ->where($where)
            ->group('shang_id')
            ->order('sort desc,shang_id asc,id asc')
            ->select()->toArray();
        array_unshift($category, ['shang_id' => 0, 'shang_title' => '全部']);

        $where2 = [];
        $where2[] = ['goods_id', '=', $goods_id];
        $where2[] = ['num', '=', 0];
        $where2[] = ['order_type', '=', $goods['type']];
        if ($shang_id) {
            $where2[] = ['shang_id', '=', $shang_id];
        }
        $data = OrderList::field('user_id,goodslist_title,goodslist_imgurl,shang_id,addtime,luck_no')
            ->append(['shang_title', 'user_info'])
            ->where($where2)
            ->where('source', '=', 1)
            ->order('id desc')
            ->paginate(15)->each(function ($item) {
                $item['user_info']['headimg'] = imageUrl($item['user_info']['headimg']);
                $item['addtime'] = date('Y-m-d H:i:s', $item['addtime']);
                $item['goodslist_imgurl'] = imageUrl($item['goodslist_imgurl']);
                return $item;
            });

        $new_data = [
            'category' => $category,
            'data' => $data->items(),
            'last_page' => $data->lastPage(),
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }




    /**
     * 下单计算金额
     */
    public function infinite_ordermoney()
    {
        $user = $this->getUser();
        $prize_num = request()->param('prize_num/d', 0);             #抽几发
        $goods_id = request()->param('goods_id/d', 0);               #盒子ID
        $use_money_is = request()->param('use_money_is/d', 0);       #0不抵扣 1抵扣
        $use_integral_is = request()->param('use_integral_is/d', 0); #0不抵扣 1抵扣
        $coupon_id = request()->param('coupon_id/d');  //优惠券

        #盒子信息
        $goods = Goodsmodel::field('title,imgurl_detail,type,price,status,is_shou_zhe')->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        $goods['imgurl_detail'] = imageUrl($goods['imgurl_detail']);
        if ($goods['type'] == 9) {
            //连击赏
            $prize_num = intval($prize_num);
            if ($prize_num > 20) {
                return $this->renderError("一次最多购买20次");
            }
        } else {
            if ($prize_num != 1 && $prize_num != 3 && $prize_num != 5 && $prize_num != 10 && $prize_num != 50  &&  $prize_num != 100) {
                return $this->renderError("请求参数错误!!!");
            }
        }
        #盒子单价
        $box_price = $goods['price'];
        //是否首抽五折
        $shou_zhe_price = 0;
        if ($goods['type'] != 5) {
            $is_chou = Order::field('id')->where([['user_id', '=', $user['id']], ['status', '=', 1]])->find();
            $is_chou2 = Order::field('id')->where([['is_shou_zhe', '=', 1], ['status', '=', 1], ['user_id', '=', $user['id']]])->find();
            if (!$is_chou && !$is_chou2 && $goods['is_shou_zhe'] == 1) {
                $shou_zhe_price = bcmul("$box_price", "0.5", 2);
            }
        }
        $goods['shou_zhe_price'] = $shou_zhe_price;
        $price = bcmul("$box_price", "$prize_num", 2);
        $price = bcsub("$price", "$shou_zhe_price", 2);
        #订单金额 微信支付金额
        $order_total = $order_zhe_total = $price;

        #首抽半价
        if ($shou_zhe_price <= 0) {

            #使用优惠券
            $coupon_price = 0;
            if (!empty($coupon_id)) {
                $coupon = CouponReceiveModel::where(['id' => $coupon_id, 'status' => 0, 'user_id' => $user['id']])->where('man_price', '<=', $price)->find();
                if ($coupon) {
                    $coupon_price = $coupon['price'];
                }
            } else {
                $coupon_id = 0;
                $coupon = CouponReceiveModel::where(['status' => 0, 'user_id' => $user['id']])->where('man_price', '<=', $price)->order('price desc')->find();
                if ($coupon) {
                    $coupon_price = $coupon['price'];
                    $coupon_id = $coupon['id'];
                }
            }
            $price = bcsub("$price", "$coupon_price", 2);

            if ($price <= 0) {
                $price = 0;
            }
            $order_zhe_total = $price;
            $zhe = 0;
            $vip_info = UserVip::where(['id' => $user['vip']])->find();
            if ($vip_info && $vip_info['discount'] > 0) {
                $zhe = $vip_info['discount'];
                $zhe_bl = bcdiv("$zhe", "10", 2);
                $order_zhe_total = $price = bcmul("$price", "$zhe_bl", 2);
            }
            #潮币抵扣
            $use_integral = 0;
            // if ($use_integral_is == 1) {
            //     if ($user['integral'] >= $price) {
            //         $use_integral = $price;
            //         $price = 0;
            //     } else {
            //         $use_integral = $user['integral'];
            //         $price = bcsub("$price", "{$user['integral']}", 2);
            //     }
            // }
            if ($use_integral_is == 1) {
                $price = $price * 100;
                if ($user['integral'] >= $price) {
                    $use_integral = $price;
                    $price = 0;
                } else {
                    $use_integral = $user['integral'];
                    $price = bcsub("$price", "{$user['integral']}", 2);
                }
                $price = $price / 100;
            }
            #余额抵扣
            $use_money = 0;
            if ($use_money_is == 1) {
                if ($user['money'] >= $price) {
                    $use_money = $price;
                    $price = 0;
                } else {
                    $use_money = $user['money']; #
                    $price = bcsub("$price", "{$user['money']}", 2);
                }
            }
        } else {
            $coupon_id = 0;
            $coupon_price = 0;
            $use_integral = 0;
            $use_money = 0;
            $zhe = 0;
        }


        #抽奖数量
        $goods['prize_num'] = $prize_num;
        $data = [
            'goods'         => $goods,
            'order_total'   => round(floatval($order_total), 2),
            'order_zhe_total' => round($order_zhe_total, 2),
            'zhe'           => round($zhe, 2),
            'price'         => round($price, 2),
            'integral'      => round($user['integral'], 2),
            'use_integral'  => round($use_integral, 2),
            'use_integral_money' => round(round($use_integral, 2) / 100, 2),
            'money'         => round($user['money'], 2),
            'use_money'     => round($use_money, 2),
            'coupon_id'     => $coupon_id,
            'coupon_price'  => round($coupon_price, 2),
        ];
        return $this->renderSuccess("请求成功", $data);
    }

    /**
     * 下单
     */
    public function infinite_orderbuy()
    {
        $user = $this->getUser();
        if (empty($user['mobile'])) {
            return $this->renderError('请先绑定手机号', [], -9);
        }
        $ad_id = request()->header('adid');
        $goods_id = request()->param('goods_id/d', 0);               #盒子ID
        $prize_num = request()->param('prize_num/d', 0);             #抽几发
        $use_money_is = request()->param('use_money_is/d', 0);       #0不抵扣 1抵扣
        $use_integral_is = request()->param('use_integral_is/d', 0); #0不抵扣 1抵扣
        $coupon_id = request()->param('coupon_id');  //优惠券
        $is_mibao = request()->param('is_mibao/d', 0);  //连击赏下 是否是抽的秘宝池  1是  0否
        $pay_way = request()->param('pay_way');  //支付

        #盒子信息
        $goods = Goodsmodel::field('id,title,imgurl_detail,type,price,status,is_shou_zhe,max_num')->where(['id' => $goods_id])
            ->find();

        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        $where = [];
        $where[] = ['user_id', '=', $user['id']];
        $where[] = ['goods_id', '=', $goods_id];
        $order_count = OrderList::where($where)->field('id')->count('id');
        if ($goods['max_num'] > 0 and $order_count >= $goods['max_num']) {
            return $this->renderError("已达上限");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        if (!in_array($goods['type'], [2, 8, 9])) {
            return $this->renderError("非法请求");
        }
        $where = [];
        $where[] = ['goods_id', '=', $goods_id];
        $where[] = ['num', '=', 0];
        $where[] = ['gailv', '>', 0];
        $where[] = ['shang_id', 'between', self::$shang_prize_id];
        #奖品信息
        if ($goods['type'] == 9 && $is_mibao == 1) {
            //秘宝池
            $where[] = ['lian_ji_type', '=', 1];
            return $this->renderError('请求错误');
        }
        $is_goodslist = GoodsList::field('id')
            ->where($where)
            ->find();
        if (!$is_goodslist) {
            return $this->renderError('暂无奖品信息');
        }
        if ($goods['type'] == 9) {
            $prize_num = intval($prize_num);
            if ($prize_num > 20) {
                return $this->renderError("一次最多购买20次");
            }

            $user_mb_number = User::where(['id' => $user['id']])->value('mb_number');
            if ($is_mibao == 1 && $prize_num > $user_mb_number) {
                return $this->renderError("秘宝池抽奖次数不足");
            }
        } else {
            if ($prize_num != 1 && $prize_num != 3 && $prize_num != 5 && $prize_num != 10 && $prize_num != 50 && $prize_num != 100) {
                return $this->renderError("请求参数错误!!!");
            }
        }

        #盒子单价
        $box_price = $goods['price'];
        //是否首抽五折
        $shou_zhe_price = 0;
        $is_shou_zhe = 0;
        if ($goods['type'] != 5) {
            $is_chou = Order::field('id')->where([['user_id', '=', $user['id']], ['status', '=', 1]])->find();
            $is_chou2 = Order::field('id')->where([['is_shou_zhe', '=', 1], ['status', '=', 1], ['user_id', '=', $user['id']]])->find();
            if (!$is_chou && !$is_chou2 && $goods['is_shou_zhe'] == 1) {
                $shou_zhe_price = bcmul("$box_price", "0.5", 2);
                $is_shou_zhe = 1;
            }
        }

        $goods['shou_zhe_price'] = $shou_zhe_price;
        $price = bcmul("$box_price", "$prize_num", 2);
        $price = bcsub("$price", "$shou_zhe_price", 2);
        #订单金额 微信支付金额
        $order_total = $order_zhe_total = $price;

        #使用折扣
        if ($is_shou_zhe == 1) {
            $coupon_id = 0;
            $coupon_price = 0;
            $use_integral = 0;
            $use_money = 0;
            #折扣
            $zhe = 0;
        } else {
            #使用优惠券
            $coupon_price = 0;
            if (!empty($coupon_id)) {
                $coupon = CouponReceiveModel::where(['id' => $coupon_id, 'status' => 0, 'user_id' => $user['id']])->where('man_price', '<=', $price)->find();
                if ($coupon) {
                    $coupon_price = $coupon['price'];
                }
            }
            $price = bcsub("$price", "$coupon_price", 2);


            if ($price <= 0) {
                $price = 0;
            }
            $order_zhe_total = $price;

            #折扣
            $zhe = 0;
            $vip_info = UserVip::where(['id' => $user['vip']])->find();
            if ($vip_info && $vip_info['discount'] > 0) {
                $zhe = $vip_info['discount'];
                $zhe_bl = bcdiv("$zhe", "10", 2);
                $order_zhe_total = $price = bcmul("$price", "$zhe_bl", 2);
            }
            #潮币抵扣
            $use_integral = 0;
            if ($use_integral_is == 1) {
                $price = $price * 100;
                if ($user['integral'] >= $price) {
                    $use_integral = $price;
                    $price = 0;
                } else {
                    $use_integral = $user['integral'];
                    $price = bcsub("$price", "{$user['integral']}", 2);
                }
                $price = $price / 100;
            }
            #余额抵扣
            $use_money = 0;
            if ($use_money_is == 1) {
                if ($user['money'] >= $price) {
                    $use_money = $price;
                    $price = 0;
                } else {
                    $use_money = $user['money']; #
                    $price = bcsub("$price", "{$user['money']}", 2);
                }
            }
        }



        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis_key = "kpw_infinite_orderbuy" . '_' . $user['id'];
        $redis_key_info = $redis->get($redis_key);
        if ($redis_key_info) {
            return $this->renderError("当前操作太快了,请等待");
        } else {
            $redis->set($redis_key, 1, 3);
        }
        Db::startTrans();
        $res = [];
        $order_num = create_order_no('MH_', 'order', 'order_num');
        #创建订单
        $res[] = $order_id = Order::insertGetId([
            'user_id'       => $user['id'],
            'order_num'     => $order_num,
            'order_total'   => $order_total, #订单金额
            'order_zhe_total' => $order_zhe_total, #订单折扣金额
            'price'         => $price, #微信支付
            'use_money'     => $use_money, #余额抵扣
            'use_integral'  => $use_integral, #潮币抵扣
            'use_score'     => 0, #积分抵扣
            'zhe'           => $zhe, #会员折扣
            'goods_id'      => $goods_id,
            'num'           => 0,
            'goods_price'   => $goods['price'],
            'goods_title'   => $goods['title'],
            'goods_imgurl'  => $goods['imgurl_detail'],
            'prize_num'     => $prize_num,
            'status'        => 0,
            'pay_type'      => $pay_way == 'ali_wap' ? 2 : 1, #1微信 2支付宝
            'order_type'    => $goods['type'],
            'addtime'       => time(),
            'coupon_id'     => $coupon_id ? $coupon_id : 0,
            'use_coupon'    => $coupon_price, #优惠券抵扣
            'is_mibao'      => $is_mibao,
            'is_shou_zhe'   => $is_shou_zhe,
            'ad_id'         => $ad_id,
            'click_id'      => $user['click_id']
        ]);
        #微信支付金额大于0
        if ($price > 0) {
            $body = '购买盒子' . $goods['title'];
            $attach = 'order_wxs';
            if ($pay_way == 'ali_wap') {
                $payRes = (new Pay())->zfpay($order_num, $price, $body, $attach . ',' . $user['openid']);
            } else {
                $payRes = (new Pay())->wxCreateOrder($order_num, $price, $user['openid'], $body, $attach);
            }
            if ($payRes['status'] == 1) {
                #结果集
                $new_data = [
                    'status' => 1,
                    'order_num' => $order_num,
                    'res' => $payRes['data'],
                ];
            } else {
                #删除redis
                $redis->del($redis_key);
                Db::rollback();
                return $this->renderError("下单失败");
            }
        } else {
            #开盒子
            $res[] = $ret = (new Notify($this->app))->infinite_drawprize_notice($user['id'], $order_id, $goods_id);
            #结果集
            $new_data = [
                'status' => 0,
                'order_num' => $order_num,
            ];
        }
        if (resCheck($res)) {
            Db::commit();
            #删除redis
            $redis->del($redis_key);
            return $this->renderSuccess("下单成功", $new_data);
        } else {
            Db::rollback();
            #删除redis
            $redis->del($redis_key);
            return $this->renderError("购买失败,请刷新重试");
        }
    }

    /**
     * 秘宝池下单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function infinite_mibao_orderbuy()
    {
        $user = $this->getUser();
        if (empty($user['mobile'])) {
            return $this->renderError('请先绑定手机号', [], -9);
        }
        $goods_id = request()->param('goods_id/d', 0);               #盒子ID
        $prize_num = request()->param('prize_num/d', 0);             #抽几发
        $is_mibao = request()->param('is_mibao/d', 0);  //连击赏下 是否是抽的秘宝池  1是  0否

        #盒子信息
        $goods = Goodsmodel::field('id,title,imgurl_detail,type,price,status')->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        if ($goods['type'] != 9) {
            return $this->renderError("非法请求");
        }

        //秘宝池
        $where = [];
        $where[] = ['goods_id', '=', $goods_id];
        $where[] = ['num', '=', 0];
        $where[] = ['real_pro', '>', 0];
        $where[] = ['shang_id', 'between', self::$shang_prize_id];
        $where[] = ['lian_ji_type', '=', 1];

        $is_goodslist = GoodsList::field('id')
            ->where($where)
            ->find();
        if (!$is_goodslist) {
            return $this->renderError('暂无奖品信息');
        }
        $prize_num = intval($prize_num);
        if ($prize_num > 20) {
            return $this->renderError("一次最多购买20次");
        }

        $user_mb_number = User::where(['id' => $user['id']])->value('mb_number');
        if ($prize_num > $user_mb_number) {
            return $this->renderError("秘宝池抽奖次数不足");
        }

        #盒子单价
        $box_price = $goods['price'];
        #订单金额 微信支付金额
        $order_total = $price = bcmul("$box_price", "$prize_num", 2);

        if ($price <= 0) {
            $price = 0;
        }

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis_key = "kpw_infinite_orderbuy" . '_' . $user['id'];
        $redis_key_info = $redis->get($redis_key);
        if ($redis_key_info) {
            return $this->renderError("当前操作太快了,请等待");
        } else {
            $redis->set($redis_key, 1, 2);
        }
        Db::startTrans();
        $res = [];
        $order_num = create_order_no('MH_', 'order', 'order_num');
        #创建订单
        $res[] = $order_id = Order::insertGetId([
            'user_id'       => $user['id'],
            'order_num'     => $order_num,
            'order_total'   => $order_total, #订单金额
            'order_zhe_total' => 0, #订单折扣金额
            'price'         => 0, #微信支付
            'use_money'     => 0, #余额抵扣
            'use_integral'  => 0, #潮币抵扣
            'use_score'     => 0, #积分抵扣
            'zhe'           => 0, #会员折扣
            'goods_id'      => $goods_id,
            'num'           => 0,
            'goods_price'   => $goods['price'],
            'goods_title'   => $goods['title'],
            'goods_imgurl'  => $goods['imgurl_detail'],
            'prize_num'     => $prize_num,
            'status'        => 0,
            'pay_type'      => 1, #1微信 2支付宝
            'order_type'    => $goods['type'],
            'addtime'       => time(),
            'coupon_id'     => 0,
            'use_coupon'    => 0, #优惠券抵扣
            'is_mibao'      => $is_mibao
        ]);

        #开盒子
        $res[] = (new Notify($this->app))->infinite_drawprize_notice($user['id'], $order_id, $goods_id);
        #结果集
        $new_data = [
            'status' => 0,
            'order_num' => $order_num,
        ];

        if (resCheck($res)) {
            Db::commit();
            #删除redis
            $redis->del($redis_key);
            return $this->renderSuccess("下单成功", $new_data);
        } else {
            Db::rollback();
            #删除redis
            $redis->del($redis_key);
            return $this->renderError("购买失败,请刷新重试");
        }
    }

    /**
     * 抽中的奖品
     */
    public function infinite_prizeorderlog()
    {
        $user = $this->getUser();
        $order_num = request()->param('order_num', '');
        $order_info = Order::field('id,goods_id,num,order_type')
            ->where('order_num', '=', $order_num)
            ->where('user_id', '=', $user['id'])
            ->find();
        if (!$order_info) {
            return $this->renderError("支付异常,请刷新重试");
        }
        #普通赏
        $data = OrderList::field('id,user_id,shang_id,goodslist_id,goodslist_title,goodslist_imgurl,goodslist_money')
            ->append(['shang_title'])
            ->where('user_id', '=', $user['id'])
            ->where('order_id', '=', $order_info['id'])
            ->where('order_type', '=', $order_info['order_type'])
            ->order('goodslist_money desc, id asc')
            ->paginate(100)->each(function ($item) {
                $item['goodslist_imgurl'] = imageUrl($item['goodslist_imgurl']);
                return $item;
            });

        //重抽卡数量
        $item_card_count = Db::name('user_item_card')->where(['user_id' => $user['id'], 'status' => 1])->count();
        $new_data = [
            'user_info' => [
                'nickname' => $user['nickname'],
                'headimg' => $user['headimg'],
            ],
            'data' => $data->items(),
            'item_card_count' => $item_card_count,
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }

    /**
     * 无限令奖励
     */
    public function infinite_give_list()
    {
        $user = $this->getUser();
        $thismonth = getConfig('give_time')['range_time'];
        $thismontharr = explode(' - ', $thismonth);
        #获取开始时间戳
        $beginThismonth = strtotime($thismontharr[0]);
        #获取结束时间戳
        $endThismonth = strtotime($thismontharr[1]);
        $consumption_total = Order::field('total')
            ->where('status', '=', 1)
            ->where('user_id', '=', $user['id'])
            ->where('addtime', 'BETWEEN', array($beginThismonth, $endThismonth))
            ->where('order_type', '=', 2)
            ->sum('order_total');
        #时间数据 消费
        $other_data = [
            'time' => date('Y-m-d', $beginThismonth) . '-' . date('Y-m-d', $endThismonth),
            'money' => $consumption_total,
        ];

        #是否领取过当前时间戳
        $time_int = $beginThismonth . '_' . $endThismonth;
        $give_money = Give::where('time_int', '=', $time_int)->order('id desc')->value('money');
        $give_money = $give_money ? $give_money : 0;
        #奖品列表
        $data = GoodsList::field('id,give_money,goods_id')
            ->append(['give_list'])
            ->where('goods_id', '=', 0)
            ->order('give_money asc,id asc')
            ->group('give_money')
            ->select()->toArray();
        foreach ($data as &$value) {
            if ($give_money >= $value['give_money']) {
                $value['is'] = 1;
            } else {
                $value['is'] = 0;
            }
        }
        $new_data = [
            'other_data' => $other_data,
            'data' => $data,
        ];
        return $this->renderSuccess('请求成功', $new_data);
    }

    /**
     * 无限令领取接口
     */
    public function infinite_give_goods()
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $thismonth = getConfig('give_time')['range_time'];
        $thismontharr = explode(' - ', $thismonth);
        #获取开始时间戳
        $beginThismonth = strtotime($thismontharr[0]);
        #获取结束时间戳
        $endThismonth = strtotime($thismontharr[1]);

        #是否领取过当前时间戳
        $time_int = $beginThismonth . '_' . $endThismonth;

        $give_money = Give::where('time_int', '=', $time_int)->order('id desc')->value('money');
        $give_money = $give_money ? $give_money : 0;

        #总消费
        $consumption_total = Order::field('total')
            ->where('status', '=', 1)
            ->where('user_id', '=', $user['id'])
            ->where('addtime', 'BETWEEN', array($beginThismonth, $endThismonth))
            ->where('order_type', '=', 2)
            ->sum('order_total');
        if ($give_money >= $consumption_total) {
            return $this->renderError("暂无可领取奖品");
        }
        #赠送商品
        $give_goods = GoodsList::where(['goods_id' => 0])
            ->where("give_money", '>', $give_money)
            ->where("give_money", '<=', $consumption_total)
            ->order('give_money asc,id asc')
            ->select()->toArray();
        if (!$give_goods) {
            return $this->renderError("暂无可领取奖品");
        }
        Db::startTrans();
        $res = [];
        #符合赠送
        $save_data = [];
        foreach ($give_goods as $value) {
            $save_data[] = [
                'order_id'      => 0,
                'user_id'       => $user_id,
                'status'        => 0, #0未操作 1选择兑换 2选择发货
                'goods_id'      => 0,
                'num'           => 0,
                'shang_id'      => $value['shang_id'],
                'goodslist_id'  => $value['id'],
                'goodslist_title'   => $value['title'],
                'goodslist_imgurl'  => $value['imgurl'],
                'goodslist_price'   => $value['price'],
                'goodslist_money'   => $value['money'],
                'goodslist_type'    => $value['goods_type'],
                'goodslist_sale_time' => $value['sale_time'],
                'addtime'           => time(),
                'prize_code'        => $value['prize_code'],
                'order_type'        => 6,
            ];
        }
        $res[] = OrderList::insertAll($save_data);
        $res[] = Give::insert([
            'user_id' => $user_id,
            'time_int' => $time_int,
            'time_date' => date('Y-m-d H:i:s', $beginThismonth) . '_' . date('Y-m-d H:i:s', $endThismonth),
            'money' => $consumption_total,
            'addtime' => time(),
        ]);
        if (resCheck($res)) {
            Db::commit();
            return $this->renderSuccess("领取成功");
        } else {
            Db::rollback();
            return $this->renderError("领取失败，请稍后重试");
        }
    }


    //进行抽奖
    public function do_draw()
    {
        $user = $this->getUser();
        if (empty($user['mobile'])) {
            return $this->renderError('请先绑定手机号', [], -9);
        }
        $goods_id = request()->param('goods_id/d', 0);               #盒子ID
        $prize_num = request()->param('prize_num/d', 1);             #抽几发
        #盒子信息
        $goods = Goodsmodel::field('id,title,imgurl_detail,type,price,status')->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        if ($goods['type'] != 7) {
            return $this->renderError("非法请求");
        }

        #奖品信息
        $is_goodslist = GoodsList::field('id')
            ->where('goods_id', '=', $goods_id)
            ->where('num', '=', 0)
            ->where('real_pro', '>', 0)
            ->where('shang_id', 'between', self::$shang_prize_id)
            ->find();
        if (!$is_goodslist) {
            return $this->renderError('暂无奖品信息');
        }
        if ($prize_num != 1) {
            return $this->renderError("请求参数错误");
        }
        $draw_num = $user['draw_num'];
        // var_dump($draw_num);
        // exit;
        if ($user['draw_num'] == 0 || bccomp("$draw_num", "$prize_num") < 0) {
            return $this->renderError("抽奖券不足,无法进行抽奖");
        }
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis_key = "kpw_infinite_orderbuy_draw" . '_' . $user['id'];
        $redis_key_info = $redis->get($redis_key);
        if ($redis_key_info) {
            return $this->renderError("当前操作太快了,请等待");
        } else {
            $redis->set($redis_key, 1, 10);
        }
        Db::startTrans();
        $res = [];
        $order_num = create_order_no('MH_', 'order', 'order_num');
        #创建订单
        $res[] = $order_id = Order::insertGetId([
            'user_id'           => $user['id'],
            'order_num'         => $order_num,
            'order_total'       => 0, #订单金额
            'order_zhe_total'   => 0, #订单折扣金额
            'price'             => 0, #微信支付
            'use_money'         => 0, #余额抵扣
            'use_integral'      => 0, #潮币抵扣
            'use_score'         => 0, #积分抵扣
            'zhe'               => 0, #会员折扣
            'goods_id'          => $goods_id,
            'num'               => 0,
            'goods_price'       => $goods['price'],
            'goods_title'       => $goods['title'],
            'goods_imgurl'      => $goods['imgurl_detail'],
            'prize_num'         => $prize_num,
            'status'            => 0,
            'pay_type'          => 1, #1微信 2支付宝
            'order_type'        => $goods['type'],
            'addtime'           => time(),
            'use_draw'          => 1
        ]);

        #开盒子
        $res[] = (new Notify($this->app))->draw_drawprize_notice($user['id'], $order_id, $goods_id);
        #结果集
        $new_data = [
            'status' => 0,
            'order_num' => $order_num,
        ];

        if (resCheck($res)) {
            Db::commit();
            #删除redis
            $redis->del($redis_key);
            return $this->renderSuccess("下单成功", $new_data);
        } else {
            Db::rollback();
            #删除redis
            $redis->del($redis_key);
            return $this->renderError("购买失败,请刷新重试");
        }
    }

    /**
     * 重抽卡重抽
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function item_card_chou(Request $request)
    {
        $user = $this->getUser();
        if (empty($user['mobile'])) {
            return $this->renderError('请先绑定手机号', [], -9);
        }
        $goods_id = request()->param('goods_id/d', 0);               #盒子ID
        $order_list_ids = request()->param('order_list_ids', "");             #重抽的ID

        #盒子信息
        $goods = Goodsmodel::field('id,title,imgurl_detail,type,price,status')->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        $order_list_ids = explode(',', trim($order_list_ids));
        if (empty($order_list_ids)) {
            return $this->renderError("参数错误");
        }

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis_key = "item_card_chou" . '_' . $user['id'];
        $redis_key_info = $redis->get($redis_key);
        if ($redis_key_info) {
            return $this->renderError("当前操作太快了,请等待");
        } else {
            $redis->set($redis_key, 1, 5);
        }

        $item_card_count = Db::name('user_item_card')->where(['user_id' => $user['id'], 'status' => 1])->whereNull('deltime')->count();
        if (1 > $item_card_count) {
            return $this->renderError("重抽卡数量不足");
        }

        foreach ($order_list_ids as $k => $v) {
            $order_list = OrderList::field('id')->where(['id' => $v, 'status' => 0])->find();
            if (!$order_list) {
                return $this->renderError("数据错误");
            }
        }

        Db::startTrans();
        $res = [];
        $order_num = create_order_no('MH_', 'order', 'order_num');
        #创建订单
        $res[] = $order_id = Order::insertGetId([
            'user_id'           => $user['id'],
            'order_num'         => $order_num,
            'order_total'       => 0, #订单金额
            'order_zhe_total'   => 0, #订单折扣金额
            'price'             => 0, #微信支付
            'use_money'         => 0, #余额抵扣
            'use_integral'      => 0, #潮币抵扣
            'use_score'         => 0, #积分抵扣
            'zhe'               => 0, #会员折扣
            'goods_id'          => $goods_id,
            'num'               => 0,
            'goods_price'       => $goods['price'],
            'goods_title'       => $goods['title'],
            'goods_imgurl'      => $goods['imgurl_detail'],
            'prize_num'         => count($order_list_ids),
            'status'            => 0,
            'pay_type'          => 1, #1微信 2支付宝
            'order_type'        => $goods['type'],
            'addtime'           => time(),
            'use_item_card'     => 1
            // 'use_item_card' => count($order_list_ids)
        ]);

        #开盒子
        $res[] = (new Notify($this->app))->item_card_notice($user['id'], $order_id, $goods_id);

        #判断是否发积分 发券
        $order = Order::where(['id' => $order_id])->find();
        $res[] = User::is_integral_coupon($order);

        $res[] = OrderList::where(['user_id' => $user['id']])->whereIn('id', $order_list_ids)->update(['is_chong' => 1, 'deltime' => time()]);

        #结果集
        $new_data = [
            'status' => 0,
            'order_num' => $order_num,
        ];

        if (resCheck($res)) {
            Db::commit();
            #删除redis
            $redis->del($redis_key);
            return $this->renderSuccess("重抽成功", $new_data);
        } else {
            Db::rollback();
            #删除redis
            $redis->del($redis_key);
            return $this->renderError("重抽失败,请刷新重试");
        }
    }

    /**
     *领主
     */
    public function ling_zhu_king(Request $request)
    {
        $goods_id = $request->param('goods_id');
        $type = $request->param('type/d', 1);

        if (!isset($goods_id) && empty($goods_id)) {
            return $this->renderSuccess('参数错误');
        }

        //查找当前领主
        $goods = Db::name('goods')->field('king_user_id,lingzhu_fan,lingzhu_shang_id')->where([['id', '=', $goods_id]])->find();
        $king_user = Db::name('user')->field('id,nickname,headimg')->where(['id' => $goods['king_user_id']])->find();
        if ($goods && $goods['king_user_id'] && $king_user) {
            $king_user['headimg'] = imageUrl($king_user['headimg']);
            $goods_king_rank = Db::name('goods_king_rank')->field('order_list_id')->where(['user_id' => $goods['king_user_id'], 'goods_id' => $goods_id])->order('id desc')->limit(1)->find();
            $order_list_id = $goods_king_rank ? $goods_king_rank['order_list_id'] : 0;
            $jiang_img = OrderList::field('goodslist_title,goodslist_imgurl')->where(['id' => $order_list_id])->find();
            $king_user['jiang_title'] = $jiang_img ? $jiang_img['goodslist_title'] : '';
            $king_user['jiang_img'] = $jiang_img ? imageUrl($jiang_img['goodslist_imgurl']) : '';
            $king_rand = Db::name('goods_king_rank')->where(['user_id' =>  $goods['king_user_id']])->where('goods_id', $goods_id)->whereNull('end_time')->field('z_nums, count')->find();
            $king_user['z_nums'] = $king_rand['z_nums'];
            $king_user['count'] = $king_rand['count'];
        } else {
            $king_user = null;
        }

        if ($type == 1) {
            //挑战人数
            $list = Db::name('goods_king_rank')
                ->alias('a')
                ->join('user b', 'a.user_id = b.id')
                ->field('a.user_id,b.nickname,b.headimg')
                ->where([['a.goods_id', '=', $goods_id]])
                ->group('a.user_id')
                ->order('a.id', 'desc')
                ->paginate(20)->each(function ($item) {
                    $item['headimg'] = imageUrl($item['headimg']);
                    return $item;
                });
        } elseif ($type == 2) {
            //领主记录
            $list = Db::name('goods_king_rank')
                ->alias('a')
                ->join('user b', 'a.user_id = b.id')
                ->field('a.user_id,a.addtime,a.end_time,b.nickname,b.headimg')
                ->where([['a.goods_id', '=', $goods_id]])
                ->order('a.id', 'desc')
                ->paginate(20)->each(function ($item) {
                    $item['headimg'] = imageUrl($item['headimg']);
                    $item['time'] = time_jian($item['addtime'], $item['end_time'] ? $item['end_time'] : time());
                    return $item;
                });
        }

        $ling_goods_list = GoodsList::field('goods_id,shang_id,title,imgurl')
            ->append(['shang_info'])
            ->where(['goods_id' => $goods_id])
            ->where(['shang_id' => $goods['lingzhu_shang_id']])
            ->where(['num' => 0])
            ->order('sort desc,shang_id asc,id asc')
            ->select();
        foreach ($ling_goods_list as &$value) {
            $value['imgurl'] = imageUrl($value['imgurl']);
        }

        $data = [];
        $data['goods']          = $goods;
        $data['king_user']      = $king_user;
        $data['list']           = $list;
        $data['ling_goods_list'] = $ling_goods_list;
        return $this->renderSuccess('请求成功', $data);
    }
}
